'use client'

import { useState, useEffect } from 'react'
import { Plus, Search, Edit, Trash2, Tag, FileText, TrendingUp, Hash, Loader2, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { tagsAPI } from '@/lib/api'
import { toast } from 'sonner'

interface Tag {
  id: string
  name: string
  slug: string
  description?: string
  color: string
  createdAt: string
  updatedAt: string
  createdBy: {
    id: string
    username: string
  }
  _count?: {
    knowledgeBases: number
  }
  // 🔴 兼容字段，用于显示
  articlesCount?: number
  usageCount?: number
}

export default function TagManagement() {
  const [tags, setTags] = useState<Tag[]>([])
  const [searchQuery, setSearchQuery] = useState('')
  const [showAddForm, setShowAddForm] = useState(false)
  const [editingTag, setEditingTag] = useState<Tag | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [formData, setFormData] = useState({
    name: '',
    slug: '',
    description: '',
    color: '#3B82F6'
  })

  // 获取标签列表
  const fetchTags = async () => {
    try {
      setIsLoading(true)
      const response = await tagsAPI.getTags()
      // 🔴 修复：根据后端接口响应格式，数据在 response.data.tags 中
      setTags(response.tags || [])
    } catch (error: any) {
      console.error('Failed to fetch tags:', error)
      toast.error(error.message || '获取标签列表失败')
    } finally {
      setIsLoading(false)
    }
  }

  // 创建标签
  const createTag = async () => {
    try {
      setIsSubmitting(true)
      await tagsAPI.createTag(formData)
      toast.success('标签创建成功')
      setShowAddForm(false)
      resetForm()
      // 🔴 确保创建成功后重新获取数据
      await fetchTags()
    } catch (error: any) {
      console.error('Failed to create tag:', error)
      toast.error(error.message || '创建标签失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 更新标签
  const updateTag = async () => {
    if (!editingTag) return

    try {
      setIsSubmitting(true)
      await tagsAPI.updateTag(editingTag.id, formData)
      toast.success('标签更新成功')
      setEditingTag(null)
      resetForm()
      // 🔴 确保更新成功后重新获取数据
      await fetchTags()
    } catch (error: any) {
      console.error('Failed to update tag:', error)
      toast.error(error.message || '更新标签失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 删除标签
  const deleteTag = async (tagId: string) => {
    if (!confirm('确定要删除这个标签吗？此操作不可撤销。')) {
      return
    }

    try {
      setIsSubmitting(true)
      await tagsAPI.deleteTag(tagId)
      toast.success('标签删除成功')
      // 🔴 确保删除成功后重新获取数据
      await fetchTags()
    } catch (error: any) {
      console.error('Failed to delete tag:', error)
      toast.error(error.message || '删除标签失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 重置表单
  const resetForm = () => {
    setFormData({
      name: '',
      slug: '',
      description: '',
      color: '#3B82F6'
    })
  }

  // 编辑标签
  const handleEdit = (tag: Tag) => {
    setEditingTag(tag)
    setFormData({
      name: tag.name,
      slug: tag.slug,
      description: tag.description || '',
      color: tag.color
    })
  }

  // 取消编辑
  const handleCancel = () => {
    setShowAddForm(false)
    setEditingTag(null)
    resetForm()
  }

  // 处理表单提交
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (editingTag) {
      updateTag()
    } else {
      createTag()
    }
  }

  // 初始化加载
  useEffect(() => {
    fetchTags()
  }, [])

  const filteredTags = tags.filter(tag =>
    tag.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    tag.description.toLowerCase().includes(searchQuery.toLowerCase())
  )

  // 🔴 修复：使用正确的字段计算统计数据
  const totalArticles = tags.reduce((sum, t) => sum + (t._count?.knowledgeBases || t.articlesCount || 0), 0)



  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex items-center space-x-2">
          <Loader2 className="h-6 w-6 animate-spin" />
          <span>加载标签数据中...</span>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">标签管理</h1>
          <p className="text-gray-600 mt-1">管理知识库内容标签</p>
        </div>
        <Button onClick={() => setShowAddForm(true)}>
          <Plus className="h-4 w-4 mr-2" />
          添加标签
        </Button>
      </div>

      {/* 标签统计 */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center space-x-2">
              <Tag className="h-5 w-5 text-blue-600" />
              <div>
                <p className="text-sm text-muted-foreground">总标签数</p>
                <p className="text-2xl font-bold">{tags.length}</p>
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center space-x-2">
              <FileText className="h-5 w-5 text-green-600" />
              <div>
                <p className="text-sm text-muted-foreground">总文章数</p>
                <p className="text-2xl font-bold">{totalArticles}</p>
              </div>
            </div>
          </CardContent>
        </Card>
                 <Card>
           <CardContent className="p-4">
             <div className="flex items-center space-x-2">
               <TrendingUp className="h-5 w-5 text-orange-600" />
               <div>
                 <p className="text-sm text-muted-foreground">标签总数</p>
                 <p className="text-2xl font-bold">{tags.length}</p>
               </div>
             </div>
           </CardContent>
         </Card>
         <Card>
           <CardContent className="p-4">
             <div className="flex items-center space-x-2">
               <Hash className="h-5 w-5 text-purple-600" />
               <div>
                 <p className="text-sm text-muted-foreground">平均使用</p>
                 <p className="text-2xl font-bold">{tags.length > 0 ? Math.round(totalArticles / tags.length) : 0}</p>
               </div>
             </div>
           </CardContent>
         </Card>
      </div>

      {/* 搜索 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">搜索标签</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="relative">
            <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="搜索标签名称或描述..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-8"
            />
          </div>
        </CardContent>
      </Card>

      {/* 标签列表 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">标签列表 ({filteredTags.length})</CardTitle>
        </CardHeader>
        <CardContent>
          {filteredTags.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              暂无标签数据
            </div>
          ) : (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {filteredTags.map((tag) => (
                <div
                  key={tag.id}
                  className="p-4 border border-border rounded-lg hover:shadow-md transition-shadow"
                >
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-center space-x-2">
                      <div 
                        className="w-4 h-4 rounded-full"
                        style={{ backgroundColor: tag.color }}
                      />
                      <h3 className="font-medium">{tag.name}</h3>
                    </div>
                                         <div className="flex items-center space-x-2">
                       {/* 标签状态和热门状态暂时不显示 */}
                     </div>
                  </div>
                  
                  <p className="text-sm text-muted-foreground mb-3 line-clamp-2">
                    {tag.description || '暂无描述'}
                  </p>
                  
                  <div className="flex items-center justify-between text-xs text-muted-foreground mb-3">
                    <span>别名: {tag.slug}</span>
                    <span>创建: {new Date(tag.createdAt).toLocaleDateString()}</span>
                  </div>
                  
                  <div className="flex items-center justify-between text-sm">
                    <div className="flex items-center space-x-4">
                      <span className="flex items-center space-x-1">
                        <FileText className="h-4 w-4" />
                        <span>{tag._count?.knowledgeBases || tag.articlesCount || 0}</span>
                      </span>
                      <span className="flex items-center space-x-1">
                        <Hash className="h-4 w-4" />
                        <span>{tag._count?.knowledgeBases || tag.usageCount || 0}</span>
                      </span>
                    </div>
                    
                    <div className="flex items-center space-x-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEdit(tag)}
                        disabled={isSubmitting}
                      >
                        <Edit className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="text-destructive hover:text-destructive"
                        onClick={() => deleteTag(tag.id)}
                        disabled={isSubmitting}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* 添加/编辑标签表单 */}
      {(showAddForm || editingTag) && (
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="text-lg">
                {editingTag ? '编辑标签' : '添加标签'}
              </CardTitle>
              <Button
                variant="ghost"
                size="sm"
                onClick={handleCancel}
                disabled={isSubmitting}
              >
                <X className="h-4 w-4" />
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid gap-4 md:grid-cols-2">
                <div>
                  <label className="text-sm font-medium">标签名称</label>
                  <Input
                    placeholder="输入标签名称"
                    value={formData.name}
                    onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                    className="mt-1"
                    required
                  />
                </div>
                <div>
                  <label className="text-sm font-medium">别名</label>
                  <Input
                    placeholder="输入别名（英文）"
                    value={formData.slug}
                    onChange={(e) => setFormData(prev => ({ ...prev, slug: e.target.value }))}
                    className="mt-1"
                    required
                  />
                </div>
              </div>
              
              <div>
                <label className="text-sm font-medium">描述</label>
                <Input
                  placeholder="输入标签描述"
                  value={formData.description}
                  onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                  className="mt-1"
                  required
                />
              </div>
              
                             <div>
                 <label className="text-sm font-medium">颜色</label>
                 <Input
                   type="color"
                   value={formData.color}
                   onChange={(e) => setFormData(prev => ({ ...prev, color: e.target.value }))}
                   className="mt-1 h-10"
                 />
               </div>
              
              <div className="flex items-center justify-end space-x-2">
                <Button
                  type="button"
                  variant="outline"
                  onClick={handleCancel}
                  disabled={isSubmitting}
                >
                  取消
                </Button>
                <Button type="submit" disabled={isSubmitting}>
                  {isSubmitting ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      {editingTag ? '更新中...' : '创建中...'}
                    </>
                  ) : (
                    editingTag ? '更新' : '创建'
                  )}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
